﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RWSBeeldbank.Common;
using RWSBeeldbank.Data;
using Windows.UI.Xaml.Data;

namespace RWSBeeldbank.DataModel
{
    public class DynamicLoadItemsSearch : ObservableCollection<MediaObjectDataItem>, ISupportIncrementalLoading 
    {
        private int _currentPage = 0; //page tracking
        private string _searchString = "";
        private int _searchResultSetSize = Constants.MAX_NR_ITEMS;

        #region ISupportIncrementalLoading Members
        public bool HasMoreItems
        {
            get { 
                bool retVal = false;

                // While the Count < the result size
                // and _searchResultSetSize > (Constants.SEARCH_PAGE_SIZE * _currentPage) = result set is bigger then what has been loaded so far

                if (this.Count <= _searchResultSetSize && _searchResultSetSize > (Constants.SEARCH_PAGE_SIZE * _currentPage))
                {
                    retVal = true;
                }

                return retVal;
            }
        }

        public Windows.Foundation.IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            return AsyncInfo.Run((ct) => LoadMoreItemsAsync(ct, count));
        }
        #endregion

        public void setSearchString(string searchString)
        {
            _searchString = searchString;
        }

        public void resetCurrentPage()
        {
            _currentPage = 0;
        }

        private async Task<LoadMoreItemsResult> LoadMoreItemsAsync(CancellationToken ct, uint count)
        {
            uint moreItems = await LoadMoreItems(count);
            return new LoadMoreItemsResult() { Count = moreItems };
        }

        private async Task<uint> LoadMoreItems(uint count)
        {
            var items = await MediaObjectDataSource.GetTitlesSearch(Constants.SEARCH_PAGE_SIZE, _currentPage * Constants.SEARCH_PAGE_SIZE, _searchString);

            this.Clear();

            foreach (var item in items)
            {
                this.Add(item);

                _searchResultSetSize = item.SearchResultSetSize;

                // add the search group to the item
                item.Group = MediaObjectDataSource._mediaObjectDataSource.AllGroups.FirstOrDefault(c => c.UniqueId.Equals(Constants.SEARCHCOLLECTIONID));
            }

            _currentPage++;

            return (uint)items.Count();
        }
    }
}
